<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="班级名">
        <el-input v-model="searchForm.className" placeholder="请输入班级名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="success" @click="showAddDialog">新增班级</el-button>
    <el-button type="info" @click="refreshClasses">刷新班级</el-button>
    <el-table :data="classes" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="classId" label="班级ID" width="100"></el-table-column>
      <el-table-column prop="classNode" label="校区"></el-table-column>
      <el-table-column prop="className" label="班级名称"></el-table-column>
      <el-table-column prop="oldClassName" label="原班级"></el-table-column>
      <el-table-column prop="classGrade" label="年级"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="390">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="confirmDeleteClass(scope.row.classId, scope.row.className)">删除</el-button>
          <el-button size="mini" @click="showClassDialog(scope.row)">添加学生</el-button>
          <el-button size="mini" @click="showEnrolledClass(scope.row)">查看班级学生</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- 添加班级的对话框 -->
    <el-dialog title="添加班级" v-model="addVisible" width="30%">
      <el-form :model="addForm">
        <el-form-item label="校区" label-width="100px">
          <el-input v-model="addForm.classNode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" label-width="100px">
          <el-input v-model="addForm.className" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原班级名称" label-width="100px">
          <el-input v-model="addForm.oldClassName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年级" label-width="100px">
          <el-input v-model="addForm.classGrade" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="addForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="addClass">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="编辑班级" v-model="editVisible" width="30%">
      <el-form :model="editForm">
        <el-form-item label="校区" label-width="100px">
          <el-input v-model="editForm.classNode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" label-width="100px">
          <el-input v-model="editForm.className" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原班级名称" label-width="100px">
          <el-input v-model="editForm.oldClassName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年级" label-width="100px">
          <el-input v-model="editForm.classGrade" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="editClass">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="选择学生" v-model="classDialogVisible" width="50%">
      <el-table :data="students" style="width: 100%" @selection-change="handleStudentSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="stuId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="stuName" label="姓名"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="classDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enrollSelectedStudents">确认添加</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="该班级的学生" v-model="enrolledClassDialogVisible" width="50%">
      <el-table :data="enrolledStudents" style="width: 100%">
        <el-table-column prop="stuId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="stuName" label="姓名"></el-table-column>
        <el-table-column prop="stuNumber" label="学号"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="DeleteStudent(scope.row.stuId, scope.row.stuName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="enrolledClassDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessageBox} from "element-plus";

export default {
  name: 'ClassList',
  data() {
    return {
      classes: [],
      searchForm: {
        className: ''
      },
      addVisible: false,
      editVisible: false,
      classDialogVisible : false,
      enrolledClassDialogVisible : false,
      addForm: {
        classId: null,
        classNode: '',
        className: '',
        oldClassName: '',
        classGrade: '',
        remark: ''
      },
      editForm: {
        classId: null,
        classNode: '',
        className: '',
        oldClassName: '',
        classGrade: '',
        remark: ''
      },
      students: [], // 存储学生数据
      selectedStudents: [], // 用于存储选中的学生
      enrolledStudents: []
    };
  },
  methods: {
    async fetchClasses(params) {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/classes/list`, params);
        this.classes = response.data;
      } catch (error) {
        console.error('Failed to fetch classes:', error);
      }
    },
    onSearch() {
      const params = {
        className: this.searchForm.className
      };
      this.fetchClasses(params);
    },
    resetForm() {
      this.searchForm.className = '';
      this.fetchClasses();
    },
    refreshClasses() {
      this.fetchClasses();
    },
    showAddDialog() {
      this.addVisible = true;
    },
    showEditDialog(row) {
      this.editForm = { ...row };
      this.editVisible = true;
    },
    async addClass() {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/classes/add`, this.addForm);
        this.classes.push(response.data); // 假设返回的新学生对象
        this.addVisible = false;
        this.resetAddForm();
        this.refreshClasses();
      } catch (error) {
        console.error('Failed to add student:', error);
      }
    },
    async editClass() {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/classes/edit`, this.editForm);
        this.classes.push(response.data); // 假设返回的新学生对象
        this.editVisible = false;
        this.refreshClasses();
      } catch (error) {
        console.error('Failed to add student:', error);
      }
    },
    showClassDialog(classInfo) {
      this.currentClass = classInfo;
      this.fetchStudents();
      this.classDialogVisible = true;
    },
    resetAddForm() {
      this.addForm.classNode = '';
      this.addForm.className = '';
      this.addForm.oldClassName = '';
      this.addForm.classGrade = '';
      this.addForm.remark = '';
    },
    confirmDeleteClass(classId, className) {
      this.$confirm(`确定要删除班级 "${className}" 吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`${process.env.VUE_APP_API_BASE_URL}/classes/delete/${classId}`)
          .then(() => {
            this.refreshClasses();
          })
          .catch(error => {
            console.error('Failed to delete class:', error);
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    async fetchStudents() {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_BASE_URL}/students/listClassName`);
        this.students = response.data;
      } catch (error) {
        console.error('Failed to fetch students:', error);
      }
    },
    handleStudentSelectionChange(selection) {
      this.selectedStudents = selection;
    },
    async enrollSelectedStudents() {
      if (this.selectedStudents.length === 0) {
        this.$message({
          message: '请选择至少一个学生',
          type: 'warning'
        });
        return;
      }
      const studentIds = this.selectedStudents.map(student => student.stuId);
      const data = {
        studentIds: studentIds,
        classId: this.currentClass.classId

      };
      try {
        await axios.post(`${process.env.VUE_APP_API_BASE_URL}/classes/enrollClass`, data);
        this.$message({
          message: '学生成功添加到班级',
          type: 'success'
        });
        this.classDialogVisible = false;
      } catch (error) {
        console.error('Failed to enroll students:', error);
        this.$message({
          message: '添加失败',
          type: 'error'
        });
      }
    },
    showEnrolledClass(classes) {
      this.fetchEnrolledStudents(classes.classId);
      this.enrolledClassDialogVisible = true;
    },
    async fetchEnrolledStudents(classId) {
      try{
        const response =await axios.get(`${process.env.VUE_APP_API_BASE_URL}/classes/enrolledStudents/${classId}`)
        this.enrolledStudents = response.data;
        this.enrolledClassDialogVisible = true;
      }catch(error) {
        console.error('Failed to fetch enrolled students:', error);
        this.$message({
          message: '获取已选学生失败',
          type: 'error'
        });
      }
    },
    DeleteStudent(stuId, stuName) {
      ElMessageBox.confirm(
          `确定要删除学生 "${stuName}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        this.deleteStudent(stuId);
      }).catch(() => {
        // 用户取消删除
      });
    },
    async deleteStudent(stuId) {
      // 发送 DELETE 请求来删除学生
      try {
        await axios.delete(`${process.env.VUE_APP_API_BASE_URL}/classes/deleteStu/${stuId}`);
        this.students = this.students.filter(student => student.stuId !== stuId);
        this.enrolledClassDialogVisible = false;
      } catch (error) {
        console.error('Failed to delete student:', error);
      }
    }
  },
  mounted() {
    this.fetchClasses(); // 页面加载时立即获取班级列表
  }
};
</script>

<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}
</style> 